package com.feiyisuo.sso.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import io.micrometer.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;

/**
 * @Author: Huanghz
 * @description: Json序列化反序列化工具
 * @date:Created in 2:35 下午 2021/5/6
 * @modifyBy:
 **/
@Slf4j
public class JsonUtils {
    private JsonUtils(){};
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    static {
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        OBJECT_MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    }
    public static ObjectMapper getObjectMapper(){
        return OBJECT_MAPPER;
    }

    /**
     * 对象转json
     *
     * @param value
     * @return
     */
    public static final String toJson(Object value) {
        if (value == null) {
            return null;
        }
        String result = null;
        if (value instanceof Serializable) {
            try {
                result = OBJECT_MAPPER.writeValueAsString(value);
            } catch (JsonProcessingException e) {
                log.error("mask error", e);
            }
        } else {
            result = value.toString();
        }

        return result;
    }

    /**
     * json转对象
     *
     * @param content
     * @param valueType
     * @return
     */
    public static <T> T parseObject(String content, Class<T> valueType) {
        T t = null;
        try {
            if (StringUtils.isEmpty(content)) {
                return null;
            }
            t = OBJECT_MAPPER.readValue(content, valueType);
        } catch (JsonProcessingException e) {
            log.error("parse object error", e);
        }

        return t;
    }

    /**
     * json转泛型对象
     *
     * @param content
     * @param valueType
     * @param <T>
     * @return
     */
    public static <T> T parseObject(String content, TypeReference<T> valueType) {
        T t = null;
        try {
            t = OBJECT_MAPPER.readValue(content, valueType);
        } catch (JsonProcessingException e) {
            log.error("parse object error", e);
        }

        return t;
    }

    public static JsonNode parseObject(String content) {
        JsonNode t = null;
        try {
            t = OBJECT_MAPPER.readTree(content);
        } catch (JsonProcessingException e) {
            log.error("parse object error", e);
        }

        return t;
    }

}
